# Reduces the number of sent packets to
# at most rate packets per second
# Note, that key events are collected and
# sent in bulk in order to not miss key events
import time

_rate = 15

_pause = 1./_rate # in secs
_last_packet = {}
_collected_keys = {}
def reducerate(block):
    devid = "none"
    if "devid" in block[0]:
        devid = block[0]["devid"]
    if devid not in _last_packet:
        _last_packet[devid] = 0.0
    if devid not in _collected_keys:
        _collected_keys[devid] = set()
    tt = time.time()
    if tt - _last_packet[devid] < _pause:
        # remember unsent key events
        _collected_keys[devid] |= set(block[0]["k"])        
        return None # stop, no further processing
    # ok, continue
    _last_packet[devid] = tt
    # send remembered keys
    block[0]["k"] = "".join(set(block[0]["k"]) | _collected_keys[devid])
    _collected_keys[devid] = set() # nothing to remember
    return block
